package com.foosun.core.util;

import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import com.foosun.core.entity.User;
import com.foosun.core.filter.SessionFilter;

/**
 * Created by Nelin on 14-3-3.
 */
public class ServerUtil {

	private static String SERVER_PATH;

	public static String getServerPath(HttpServletRequest request) {
		if (SERVER_PATH == null) {
			SERVER_PATH = request.getScheme() + "://" + request.getServerName()
					+ ":" + request.getServerPort() + request.getContextPath();
		}
		return SERVER_PATH;
	}

	public static final String getValueUTF8(HttpServletRequest request,
			String parameterName) throws UnsupportedEncodingException {
		String value = request.getParameter(parameterName);
		if (value == null) {
			return null;
		}
		value = encodingUTF8(request, value);
		// else 默认为utf8
		return value;
	}

	public final String getValueUTF8(String value)
			throws UnsupportedEncodingException {
		if (value == null) {
			return null;
		}
		value = new String(value.getBytes("ISO8859-1"), "UTF-8");
		return value;
	}

	public static Integer getIntValue(HttpServletRequest request,
			String parameterName, int defaultValue) {
		int value = defaultValue;
		try {
			String stringValue = getValueUTF8(request, parameterName);
			if (stringValue != null) {
				value = Integer.parseInt(stringValue);
			}
		} catch (Exception e) {
		}
		return value;
	}

	private static String encodingUTF8(HttpServletRequest request, String value)
			throws UnsupportedEncodingException {
		String encoding = request.getCharacterEncoding();
		String result = value;
		if (("ISO8859-1".equalsIgnoreCase(encoding))) {
			result = new String(value.getBytes("ISO8859-1"), "UTF-8");
		}
		return result;
	}
	
	/**
	 * 獲取會話中存儲的用戶信息
	 * @param request
	 * @return
	 */
	public static User getLoginUser(HttpServletRequest request) {
		return (User) request.getSession().getAttribute(SessionFilter.USER);
	}

}
